package org.tio.http.apitool.page;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author tanyaowu
 * @param <T>
 */
public class SetPageable<T> extends AbstractPageable {
	@SuppressWarnings("unused")
	private static Logger log = LoggerFactory.getLogger(SetPageable.class);

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	}

	private Set<T> allData = null;

	public SetPageable() {
	}

	/**
	 * 
	 * @param pageSize
	 * @param pageIndex
	 * @param recordCount
	 * @param currentPageData
	 */
	public SetPageable(int pageSize, int pageIndex, long recordCount, List<T> currentPageData) {
		this.pageSize = processPageSize(pageSize);
		this.pageIndex = processPageIndex(pageIndex);
		this.recordCount = recordCount;
		this.data = currentPageData;
	}

	/**
	 * 
	 * @param pageSize
	 * @param pageIndex
	 * @param allData
	 */
	public SetPageable(int _pageSize, int _pageIndex, Set<T> _allData) {
		this(_pageSize, _pageIndex, _allData, null);
	}

	/**
	 * 
	 * @param _pageSize
	 * @param _pageIndex
	 * @param _allData
	 * @param _recordCount 如果_allData就是所有数据，则可以传null，否则需要把真实的记录数传过来
	 */
	public SetPageable(int _pageSize, int _pageIndex, Set<T> _allData, Integer _recordCount) {
		this.pageSize = processPageSize(_pageSize);
		this.pageIndex = processPageIndex(_pageIndex);

		this.allData = _allData;

		if (_recordCount != null) {
			this.recordCount = _recordCount;
		} else {
			if (_allData != null) {
				this.recordCount = _allData.size();
			} else {
				this.recordCount = 0;
			}
		}

		if (this.isPagination) {
			long pageCount = calculatePageCount(this.pageSize, recordCount);
			if (this.pageIndex > pageCount) {
				this.pageIndex = pageCount;
			}
			if (this.pageIndex <= 0) {
				this.pageIndex = 1;
			}

			List<T> data1 = new ArrayList<T>();

			int startIndex = (int) (this.pageIndex - 1) * this.pageSize;
			int endIndex = (int) (this.pageIndex) * this.pageSize;

			if (this.allData == null) {
				endIndex = 0;
			} else if (endIndex > allData.size()) {
				endIndex = allData.size();
			}

			int i = 0;
			synchronized (_allData) {
				for (T t : allData) {
					if (i >= endIndex) {
						break;
					}
					if (i < startIndex) {
						i++;
						continue;
					}
					if (i >= startIndex && i < endIndex) {
						data1.add(t);
						i++;
						continue;
					}
				}
			}

			this.data = data1;
		} else {
			this.data = allData;
		}
	}

	@Override
	public void reload() {
		//		final List<Integer> piDigits = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9};
	}

}
